package com.example.demo.web.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.demo.domain.base.BaseResult;
import com.example.demo.domain.base.PageResult;
import com.example.demo.domain.param.AssignRoleRequest;
import com.example.demo.domain.param.UserQueryParam;
import com.example.demo.domain.param.UserUpdateParam;
import com.example.demo.domain.vo.UserVO;
import com.example.demo.exception.BizException;
import com.example.demo.exception.ErrorConstants;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author haochen78
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/info")
    public BaseResult<UserVO> info() {
        return BaseResult.success(userService.userInfo(StpUtil.getLoginIdAsString()));
    }

    /**
     * 获取用户列表
     *
     * @return 用户VO列表
     */
    @PostMapping("/list")
    public BaseResult<PageResult<UserVO>> list(@RequestBody UserQueryParam param) {
        return BaseResult.success(userService.userList(param));
    }

    /**
     * 获取用户列表
     *
     * @return 用户VO列表
     */
    @PostMapping("/update")
    public BaseResult<Void> list(@RequestBody UserUpdateParam param) {
        userService.userUpdate(param);
        return BaseResult.success();
    }

    /**
     * 创建用户
     *
     * @return 用户VO列表
     */
    @PostMapping("/create")
    public BaseResult<Void> create(@RequestBody UserUpdateParam param) {
        userService.create(param);
        return BaseResult.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete")
    public BaseResult<Void> delete(@RequestParam Long id) {
        userService.delete(id);
        return BaseResult.success();
    }


    /**
     * 用户分配角色
     *
     * @param userId 用户ID
     * @param req    角色分配请求参数
     * @return 分配结果
     */
    @PostMapping("/{userId}/roles")
    public BaseResult<Void> assignRoles(@PathVariable Long userId, @RequestBody AssignRoleRequest req) {
        boolean success = userService.assignRoles(userId, req.getRoleIds());
        if (!success) {
            throw new BizException(ErrorConstants.OPERATION_FAIL, "分配失败");
        }
        return BaseResult.success();
    }
}
